<?php

namespace App\Http\Controllers\Admin;

use App\Model\Earn;
use App\Model\Tixian;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Toastr;

class TixianController extends Controller
{
    public function index(Request $request){
        $name = $request->input('name','');
        $search = [
            'name' => $name,
        ];
        $sql = Tixian::leftJoin('users','tixian.uid','=','users.id')
            ->select('tixian.*','users.name as username');
        $name && $sql->where('users.name','like','%'.$name.'%');
        $data = $sql->orderby('id','desc')->orderby('status','asc')->paginate(20);
        foreach ($data as $k => $v){
            $total = Earn::where('uid',$v->uid)->sum('money');
            $tixian = Tixian::where('uid',$v->uid)->sum('money');
            $data[$k]['balance'] = $total - $tixian;
        }
        return view('admin.tixian.index',['data'=>$data,'search'=>$search]);

    }

    public function up_down(Request $request){
        $return = array();
        do{
            $id = $request->input('id');
            $money = $request->input('money');
            $balance = $request->input('balance');
            if($money > $balance){
                $return['code'] = 102;
                $return['message'] = '余额不足';
                Toastr::error('余额不足');
                break;
            }
            if(empty($id)){
                $return['code'] = 101;
                $return['message'] = '缺少参数';
                break;
            }
            $info = Tixian::where('id',$id)->first();
            if(empty($info)){
                $return['code'] = 102;
                $return['message'] = '对象不存在';
                break;
            }
            $info->status = 1;
            $info->save();
            Toastr::success('操作成功');
            $return['code'] = 0;
            $return['message'] = '操作成功';
            break;

        }while (false);
        return response()->json($return);
    }
}
